package com.spatio.serving.basic.service.template.core.component.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spatio.serving.basic.service.template.common.domain.*;
import com.spatio.serving.basic.service.template.common.dto.dify.DifyCommon;
import com.spatio.serving.basic.service.template.common.req.AskSimpleReq;
import com.spatio.serving.basic.service.template.core.biz.DiaLogBiz;
import com.spatio.serving.basic.service.template.core.component.service.MealService;

import com.spatio.serving.basic.service.template.core.component.service.UserService;
import com.spatio.serving.basic.service.template.mysql.mapper.MealMapper;
import com.spatio.serving.basic.service.template.mysql.mapper.UserMapper;
import org.apache.poi.ss.formula.functions.T;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class MealServiceImpl implements MealService {
    @Autowired
    private MealMapper mealMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DiaLogBiz diaLogBiz;
    @Autowired
    private com.spatio.serving.basic.service.template.core.component.invoker.createUserDocInvoker createUserDocInvoker;


    @Override
    public boolean update_meal(MealDo meal) {
        boolean flag = mealMapper.update_meal(meal);
        return flag;
    }

    @Override
    public List<MealDo> queryBydate(Integer user_id, LocalDate time) {
        List<MealDo> res =mealMapper.queryBydate(user_id,  time);
        return res;
    }


    @Override
    public JSONArray queryFoodLog(BigInteger user_id,String messageId) {
        JSONArray foodLog= mealMapper.queryFoodLog(user_id,messageId);
        return foodLog;
    }

    @Override
    public List<String> queryUrlLog(BigInteger user_id, String conversationId) {
        List<String>imageUrl=mealMapper.queryUrlLog(user_id,conversationId);
        return imageUrl;
    }

    @Override
    public boolean completeRecord(BigInteger user_id ,JSONObject completeFood) throws IOException {
        boolean flag=true;
        JSONArray foodList=  completeFood.getJSONArray("list_data");
        for(int i =0 ;i<foodList.size();i++){
            mealMapper.completeRecord(user_id,  foodList.get(i));
        }
        //boolean flag = mealMapper.completeRecord(user_id,);
        return flag;
    }

    @Override
    public boolean deleteFood(BigInteger user_id, String uuid) {
        boolean flag = mealMapper.deleteFood(user_id,uuid);
       

        return flag;
    }
    
    @Override
    public HistoryCaloriesDo queryHistory(BigInteger userId, LocalDate time) {
        HistoryCaloriesDo historyCalories ;
        historyCalories=userMapper.findByIdAndTime(userId);
        historyCalories.setDate(time);
        //all_food=mealMapper.findHistory(userId,time);
        List<mutliFoodRecordDo> allFoodList= mealMapper.findHistory(userId,time);
        historyCalories.setDay_all_food(allFoodList);
        for(int i =0;i<allFoodList.size();i++){
            historyCalories.setTotal_calories(historyCalories.getTotal_calories()+allFoodList.get(i).getCalories());
            historyCalories.setTotal_carbs(historyCalories.getTotal_carbs()+allFoodList.get(i).getCarbs());
            historyCalories.setTotal_fats(historyCalories.getTotal_fats()+allFoodList.get(i).getFats());
            historyCalories.setTotal_proteins(historyCalories.getTotal_proteins()+allFoodList.get(i).getProteins());
        }
        return historyCalories;
    }

    @Override
    public HistoryCaloriesDo queryByKind(BigInteger userId, LocalDate time, String kind) {
        HistoryCaloriesDo historyCalories = new HistoryCaloriesDo();
        List<mutliFoodRecordDo> allFoodList= mealMapper.queryByKind(userId,time,kind);
        historyCalories.setDay_all_food(allFoodList);
        historyCalories.setUser_id(userId);
        return historyCalories;
    }

    @Override
    public boolean changeFood(BigInteger userId, JSONObject changedFood) {
        boolean flag=true;
        JSONArray foodList= changedFood.getJSONArray("list_data");
        for(int i =0;i<foodList.size();i++){
            mealMapper.changeFood(userId,foodList.get(i));

        }
        return flag;
    }

    @Override
    public void recommendFood(BigInteger userId, JSONObject recommendParams, HttpServletResponse res) throws IOException {
        AskSimpleReq req = new AskSimpleReq();
        req.setIdempotentId(new Random().ints(5).toString());
        req.setDifyConversationId("");

        Map<String,Object>record_map=new HashMap<>();
        //获取状态
        int state;
        String recommend_type=recommendParams.getString("recommend_type");
        LocalDate time = LocalDate.parse(recommendParams.getString("time"));
//        JSONArray foodRecord = new JSONArray();
        if(recommend_type.equals("记录")){
            state =2;
            List<mutliFoodRecordDo> needrecommend_food=mealMapper.queryBystates(userId,state,time);
            //获得当日已经摄入卡路里数
            MealStaticsDo mealStatics = mealMapper.queryToday(userId,time);
            //如果第一次保存，先取默认值
            if(mealStatics==null){
                mealStatics = new MealStaticsDo();
            }
            //获得每日应该摄入卡路里数
            UserInfoDo targetInfo=userMapper.findById(userId);
            record_map.put("panduan", "记录");
            record_map.put("record", "当日应摄入剩余卡路里量："+Double.toString(targetInfo.getTarget_calories()-mealStatics.getTotal_calories())+
                    "当日应摄入剩余蛋白质量"+Double.toString(targetInfo.getTarget_proteins()-mealStatics.getTotal_proteins())+
                    "当日应摄入剩余脂肪："+Double.toString(targetInfo.getTarget_fats()-mealStatics.getTotal_fats())+
                    "当日应摄入剩余碳水化合物"+Double.toString(targetInfo.getTarget_carbs()-mealStatics.getTotal_carbs()));
            req.setQuestionText(needrecommend_food.toString());
            createUserDocInvoker.createOrUpdateDoc(userId);
            diaLogBiz.recommendFoodStream(userId,req,res,record_map);
            for (int i =0;i<needrecommend_food.size();i++){
                String uuid = needrecommend_food.get(i).getUuid();
                boolean flag= mealMapper.changState(userId,uuid);
            }

        }else if (recommend_type.equals("主页")){
            state=1;
            List<mutliFoodRecordDo> needrecommend_food=mealMapper.queryBystates(userId,state,time);
            String ss  = needrecommend_food.toString();
            //获得当日已经摄入卡路里数
            MealStaticsDo mealStatics = mealMapper.queryToday(userId,time);
            //如果第一次保存，先取默认值
            if(mealStatics==null){
                mealStatics = new MealStaticsDo();
            }

            //获得每日应该摄入卡路里数
            UserInfoDo targetInfo=userMapper.findById(userId);
            record_map.put("panduan", "主页");
            record_map.put("record", "当日应摄入剩余卡路里量："+Double.toString(targetInfo.getTarget_calories()-mealStatics.getTotal_calories())+
                    "当日应摄入剩余蛋白质量"+Double.toString(targetInfo.getTarget_proteins()-mealStatics.getTotal_proteins())+
                    "当日应摄入剩余脂肪："+Double.toString(targetInfo.getTarget_fats()-mealStatics.getTotal_fats())+
                    "当日应摄入剩余碳水化合物"+Double.toString(targetInfo.getTarget_carbs()-mealStatics.getTotal_carbs()));
            req.setQuestionText(needrecommend_food.toString());
            diaLogBiz.recommendFoodStream(userId,req,res,record_map);
        }else if (recommend_type.equals("历史")){
            state=1;
            List<mutliFoodRecordDo> needrecommend_food=mealMapper.queryBystates(userId,state,time);
            //获得当日已经摄入卡路里数
            MealStaticsDo mealStatics = mealMapper.queryToday(userId,time);
            //如果第一次保存，先取默认值
            if(mealStatics==null){
                mealStatics = new MealStaticsDo();
            }
            //获得每日应该摄入卡路里数
            UserInfoDo targetInfo=userMapper.findById(userId);
            record_map.put("panduan", "历史");
            record_map.put("record", "当日应摄入剩余卡路里量："+Double.toString(targetInfo.getTarget_calories()-mealStatics.getTotal_calories())+
                    "当日应摄入剩余蛋白质量"+Double.toString(targetInfo.getTarget_proteins()-mealStatics.getTotal_proteins())+
                    "当日应摄入剩余脂肪："+Double.toString(targetInfo.getTarget_fats()-mealStatics.getTotal_fats())+
                    "当日应摄入剩余碳水化合物"+Double.toString(targetInfo.getTarget_carbs()-mealStatics.getTotal_carbs()));
            req.setQuestionText(needrecommend_food.toString());
            diaLogBiz.recommendFoodStream(userId,req,res,record_map);
        }

    }
}
